﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using mtTools;
using mtWebDraw.Common;
using mtWebDraw.Models;
using mtWebDraw.DAL;
using System.Text;
using System.Text.RegularExpressions;

namespace mtWebDraw.Controllers
{
    /// <summary>
    /// 业务处理
    /// </summary>
    public class AjaxController : Controller
    {

        #region 用户登陆退出及查询是否登陆

        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <returns></returns>
        public ActionResult UserLogin()
        {
            Success res = null;

            string name = Request["loginName"];
            string password = Request["loginPassword"];

            if (name.IsNullOrWhiteSpace() || password.IsNullOrWhiteSpace())
                res = new Success(-1, null, "用户名及密码不可为空！");
            else
            {
                var loginCount = CacheHelper.GetCache(CacheData.keyLoginLock + name); //已经连续登陆次数
                loginCount = loginCount == null ? 1 : loginCount;
                var maxLoginCount = 6; //+1为最多可连续尝试登陆次数

                //登陆失败指定次则锁定帐户禁止再登陆，以防止有人破解；修改用户密码则解除登陆锁定：可修改为原密码
                if ((int)loginCount > maxLoginCount)
                    res = new Success(-3, null, "由于连续登陆失败此帐户已被锁定！已经尝试登陆" + loginCount.ToString() + "次！1小时后自动解锁。");
                else
                {
                    var Where = NH.CreateWhere("UserName", name.Trim());
                    Where.Add("Password", password.MD5());
                    IList<tUser> list = NHibernateDal.Select<tUser>(Where);

                    if (list.Count > 0) //未停用
                    {
                        if (list[0].IsStop == false)
                        {
                            User user = new User();
                            user.ID = list[0].ID;
                            user.UserName = list[0].UserName;
                            user.FullName = list[0].FullName;
                            user.IsAdmin = list[0].IsAdmin;

                            Session["user"] = user;
                            res = new Success(1, user, "");
                        }
                        else
                            res = new Success(0, null, "您的帐号已经被停用！");
                    }
                    else
                        res = new Success(-2, null, "您输入的用户名或密码不正确！还可尝试登陆" + (maxLoginCount - (int)loginCount).ToString() + "次！");
                }

                CacheHelper.RemoveCache(CacheData.keyLoginLock + name);
                if (Session["user"] == null)
                    CacheHelper.InsertCache(CacheData.keyLoginLock + name, (int)loginCount + 1, 60 * 1); //1小时有效
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 用户退出
        /// </summary>
        /// <returns></returns>
        public ActionResult UserExit()
        {
            Session["user"] = null;
            var res = new Success(1, null, "");
            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 获取当前登陆用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginUserInfo()
        {
            Success res = null;

            object obj = Session["user"];
            if (obj != null)
            {
                User user = (User)obj;
                res = new Success(1, user, "");
            }
            else
                res = new Success(0, null, "您还未登陆或已超时！");

            return Content(res.JSONSerialize());
        }

        #endregion

        #region 下拉选择信息

        /// <summary>
        /// 部门信息下拉列表
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectDepartmentList()
        {
            return Content(CacheData.GetSelectDepartmentList());
        }

        /// <summary>
        /// 用户信息下拉列表
        /// </summary>
        /// <returns></returns>
        public ActionResult SelectUserList()
        {
            return Content(CacheData.GetSelectUserList(Request["DepartmentID"]));
        }

        #endregion

        #region 部门管理

        /// <summary>
        /// 查询部门信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DepartmentList()
        {
            Success res = null;

            object obj = Session["user"];
            if (obj != null)
            {
                var list = CacheData.GetDepartmentList();
                res = new Success(1, list, "");
            }
            else
                res = new Success(0, null, "您还未登陆或已超时！");

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 编辑部门信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DepartmentEdit()
        {
            Success res = null;

            string FullName = Request["FullName"];

            object sUser = Session["user"];

            if (FullName.IsNullOrWhiteSpace())
                res = new Success(-1, null, "部门名称不可为空！");
            else if (sUser == null)
                res = new Success(-2, null, "您还未登陆或已登陆超时，请先登陆！");
            else if (((User)sUser).UserName != CacheData.sysadmin)
                res = new Success(-3, null, "非超级管理员用户无权操作！");
            else
            {
                string id = Request["ID"];
                string Caption = Request["Caption"];

                var obj = new tDepartment();
                obj.FullName = FullName;
                obj.Caption = Caption;
                if (id.IsGuid())
                {
                    obj.ID = id.ToGuid();
                    var isOK = NHibernateDal.Update<tDepartment>(obj);
                    res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");
                }
                else
                {
                    obj.ID = Guid.NewGuid();
                    var isOK = NHibernateDal.Insert<tDepartment>(obj);
                    res = new Success(isOK != null ? 1 : 0, null, isOK != null ? "" : "数据库操作失败！");
                }

                CacheData.ClearDepartmentList();
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 删除部门信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DepartmentDelete()
        {
            Success res = null;

            string id = Request["ID"];

            object sUser = Session["user"];

            if (!id.IsGuid())
                res = new Success(-1, null, "要删除的ID必须指定！");
            else if (sUser == null)
                res = new Success(-2, null, "您还未登陆或已登陆超时，请先登陆！");
            else if (((User)sUser).UserName != CacheData.sysadmin)
                res = new Success(-3, null, "非超级管理员用户无权操作！");
            else
            {
                var Where = NH.CreateWhere("DepartmentID", id.ToGuid());
                var count = NHibernateDal.Count<tUser>(Where);
                if (count > 0)
                    res = new Success(-4, null, "尚有用户属于此部门，无法删除！");
                else
                {
                    var isOK = NHibernateDal.Delete<tDepartment>(id.ToGuid());
                    res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");

                    CacheData.ClearDepartmentList();
                }
            }

            return Content(res.JSONSerialize());
        }

        #endregion

        #region 用户管理

        /// <summary>
        /// 查询用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult UserList()
        {
            Success res = null;

            object sUser = Session["user"];
            if (sUser != null)
            {
                var list = GetCurrUserList(Request["DepartmentID"], (User)sUser);
                res = new Success(1, list, "");
            }
            else
                res = new Success(0, null, "您还未登陆或已超时！");

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 获取仅有当前用户授权码的用户列表
        /// </summary>
        private IList<tUser> GetCurrUserList(string DepartmentID, User user)
        {
            var list = CacheData.GetUserList(DepartmentID);
            if (user.UserName == CacheData.sysadmin)
                return list;

            var str = list.JSONSerialize();
            var list2 = str.JSONDeserialize<IList<tUser>>();
            foreach (var item in list2)
            {
                if (item.ID != user.ID)
                {
                    item.AuthCode = "";
                }
            }
            return list2;
        }

        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult UserEdit()
        {
            Success res = null;

            string UserName = Request["UserName"];
            string id = Request["ID"];

            ////放个线上体验环境时禁止修改超级管理员以造成登陆不上
            //if (UserName == CacheData.sysadmin)
            //    return Content((new Success(-2, null, "不要恶意破坏体验环境，体验环境禁止修改超级管理员！")).JSONSerialize());

            object sUser = Session["user"];

            if (UserName.IsNullOrWhiteSpace())
                res = new Success(-2, null, "用户名不可为空！");
            else if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已登陆超时，请先登陆！");
            else if (((User)sUser).IsAdmin == false && (id.IsGuid() && id.ToGuid() == ((User)sUser).ID) == false)
                res = new Success(-3, null, "非管理员用户及用户本人无权操作！");
            else
            {
                string Password = Request["Password"];
                string IsAdmin = Request["IsAdmin"];
                string DepartmentID = Request["DepartmentID"];
                string FullName = Request["FullName"];
                string Email = Request["Email"];
                string Mobile = Request["Mobile"];
                string IsStop = Request["IsStop"];
                string Remark = Request["Remark"];

                UserName = UserName.Trim();
                var nameList = NHibernateDal.Select<tUser>(NH.CreateWhere("UserName", UserName));
                if (nameList.Count > 0 && id.IsGuid() && nameList[0].ID != id.ToGuid()) //允许修改用户名
                    res = new Success(-4, null, "当前用户名已存在！");
                else if (!id.IsGuid() && Password.IsNullOrWhiteSpace())
                    res = new Success(-5, null, "新建用户必须为用户设置密码，密码不得为空或由纯空格组成！");
                else if (!DepartmentID.IsGuid())
                    res = new Success(-5, null, "用户所属部门不能为空，请检查输入！");
                else if (IsAdmin.IsExtChecked() && ((User)sUser).UserName != CacheData.sysadmin && (id.IsGuid() && id.ToGuid() == ((User)sUser).ID) == false)
                    res = new Success(-6, null, "管理员帐号信息仅限本人与超级管理员可设置与修改！");
                else if (!Email.IsNullOrWhiteSpace() && !(new Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")).Match(Email).Success)
                    res = new Success(-5, null, "邮箱格式不正确，请检查输入！");
                else if (!Mobile.IsNullOrWhiteSpace() && !(new Regex(@"(?:\(?[0\+]?\d{1,3}\)?)[\s-]?(?:0|\d{1,4})[\s-]?(?:(?:13\d{9})|(?:\d{7,8}))")).Match(Mobile).Success)
                    res = new Success(-5, null, "手机号码格式不正确，请检查输入！");
                else
                {
                    var obj = new tUser();
                    obj.UserName = UserName;
                    obj.DepartmentID = DepartmentID.ToGuid();
                    obj.FullName = FullName;
                    obj.Email = Email;
                    obj.Mobile = Mobile;
                    obj.Remark = Remark;

                    tUser user = !id.IsGuid() ? null : NHibernateDal.Select<tUser>(id.ToGuid());
                    if (user != null && user.UserName == CacheData.sysadmin && (UserName != CacheData.sysadmin || !IsAdmin.IsExtChecked() || IsStop.IsExtChecked()))
                        res = new Success(-7, null, "超级管理员用户不可以被修改用户名、取消管理员及停用帐号，但您可以修改密码！");
                    else if (user != null && user.IsAdmin && ((User)sUser).UserName != CacheData.sysadmin && (id.IsGuid() && id.ToGuid() == ((User)sUser).ID) == false)
                        res = new Success(-6, null, "管理员帐号信息仅限本人与超级管理员可设置与修改！");
                    else
                    {
                        if (id.IsGuid())
                        {
                            if (user == null)
                                res = new Success(-8, null, "当前用户不存在！");
                            else
                            {
                                obj.ID = id.ToGuid();
                                obj.CreateTime = user.CreateTime;

                                obj.Password = Password.IsNullOrWhiteSpace() ? user.Password : Password.MD5();
                                obj.AuthCode = user.AuthCode;

                                obj.IsAdmin = ((User)sUser).UserName == CacheData.sysadmin ? IsAdmin.IsExtChecked() : (user.IsAdmin ? IsAdmin.IsExtChecked() : user.IsAdmin);
                                if (user.IsAdmin) //原为管理员用户
                                    obj.IsStop = ((User)sUser).UserName == CacheData.sysadmin ? IsStop.IsExtChecked() : (!user.IsStop ? IsStop.IsExtChecked() : user.IsStop);
                                else //原为普通用户
                                    obj.IsStop = ((User)sUser).IsAdmin ? IsStop.IsExtChecked() : (!user.IsStop ? IsStop.IsExtChecked() : user.IsStop);

                                var isOK = NHibernateDal.Update<tUser>(obj);
                                res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");
                            }
                        }
                        else
                        {
                            obj.ID = Guid.NewGuid();
                            obj.CreateTime = DateTime.Now;

                            obj.Password = Password.MD5();
                            obj.AuthCode = Guid.NewGuid().ToString().Replace("-", "").ToLower();

                            obj.IsAdmin = IsAdmin.IsExtChecked();
                            obj.IsStop = IsStop.IsExtChecked();

                            var isOK = NHibernateDal.Insert<tUser>(obj);
                            res = new Success(isOK != null ? 1 : 0, null, isOK != null ? "" : "数据库操作失败！");
                        }

                        //修改用户密码则解除登陆锁定：可修改为原密码
                        if (user != null && !Password.IsNullOrWhiteSpace())
                            CacheHelper.RemoveCache(CacheData.keyLoginLock + user.UserName);

                        CacheData.ClearUserList();
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 停用/恢复用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult UserStop()
        {
            Success res = null;

            string id = Request["ID"];

            object sUser = Session["user"];

            if (!id.IsGuid())
                res = new Success(-2, null, "要停用的ID必须指定！");
            else if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已登陆超时，请先登陆！");
            else if (((User)sUser).IsAdmin == false && (id.IsGuid() && id.ToGuid() == ((User)sUser).ID) == false)
                res = new Success(-3, null, "非管理员用户及本人无权操作！");
            else
            {
                var user = NHibernateDal.Select<tUser>(id.ToGuid());
                if (user == null)
                    res = new Success(-4, null, "当前用户不存在！");
                else if (user.IsAdmin && ((User)sUser).UserName != CacheData.sysadmin && (id.IsGuid() && id.ToGuid() == ((User)sUser).ID) == false)
                    res = new Success(-5, null, "管理员用户仅超级管理员和本人可以停用/恢复！");
                else if (user.UserName == CacheData.sysadmin)
                    res = new Success(-6, null, "超级管理员用户不可以被停用！");
                else
                {
                    var ist = false;
                    if (user.IsAdmin) //原为管理员用户
                        ist = ((User)sUser).UserName == CacheData.sysadmin ? !user.IsStop : (!user.IsStop ? !user.IsStop : user.IsStop);
                    else //原为普通用户
                        ist = ((User)sUser).IsAdmin ? !user.IsStop : (!user.IsStop ? !user.IsStop : user.IsStop);

                    if ((!user.IsStop) != ist)
                        res = new Success(-7, null, "您可能没有权限进行本此操作！");
                    else
                    {
                        user.IsStop = !user.IsStop;

                        var isOK = NHibernateDal.Update<tUser>(user);
                        res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");

                        CacheData.ClearUserList();
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 刷新用户授权码
        /// </summary>
        /// <returns></returns>
        public ActionResult UserRefAuthCode()
        {
            Success res = null;

            string id = Request["ID"];

            object sUser = Session["user"];

            if (!id.IsGuid())
                res = new Success(-2, null, "要刷新用户授权码的ID必须指定！");
            else if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已登陆超时，请先登陆！");
            else if (((User)sUser).UserName != CacheData.sysadmin && (id.IsGuid() && id.ToGuid() == ((User)sUser).ID) == false)
                res = new Success(-3, null, "非超级管理员用户及用户本人无权操作！");
            else
            {
                var user = NHibernateDal.Select<tUser>(id.ToGuid());
                if (user == null)
                    res = new Success(-4, null, "当前用户不存在！");
                else
                {
                    user.AuthCode = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    var isOK = NHibernateDal.Update<tUser>(user);
                    res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");

                    CacheData.ClearUserList();
                }
            }

            return Content(res.JSONSerialize());
        }

        #endregion

        #region 流程图管理：单个流程图信息缓存

        /// <summary>
        /// 查询流程图信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ChartList()
        {
            Success res = null;

            object sUser = Session["user"];
            if (sUser != null)
            {
                var IsAll = Request["IsAll"] ?? "0"; //是否显示所有数据；0-仅显示所有者为自己和被授权列表，1-所有用户数据【超级管理员专用】
                var IsDelete = Request["IsDelete"]; //是否显示删除的内容：0-仅显示未删除，1-仅显示已删除，null-所有

                string where = "";

                if (((User)sUser).UserName != CacheData.sysadmin || IsAll != "1") //仅显示所有者为自己和被授权列表
                {
                    where = "Owner = '" + ((User)sUser).ID.ToString() + "'";

                    //拼接授权流程图ID
                    var clist = CacheData.GetUserChartCodeList(((User)sUser).ID);
                    if (clist.Count > 0)
                        where = "(" + where + " or ID in ('" + string.Join("','", clist.Select(p => p.ChartID.ToString()).ToList()) + "'))";
                }

                //是否显示删除的内容：0-仅显示未删除，1-仅显示已删除，null-所有
                if (IsDelete != null && IsDelete == "0") //仅显示未删除
                    where = (where == "" ? "" : where + " and ") + "IsDelete = '0'";
                else if (IsDelete != null && IsDelete == "1") //仅显示已删除
                    where = (where == "" ? "" : where + " and ") + "IsDelete = '1'";

                string sql = "select * from tChart" + (where == "" ? "" : " where " + where) + " Order By CreateTime Asc";

                var list = NHibernateDal.Select<tChart>(sql);
                res = new Success(1, list, "");
            }
            else
                res = new Success(0, null, "您还未登陆或已超时！");

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 编辑流程图信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ChartEdit()
        {
            Success res = null;

            object sUser = Session["user"];

            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已登陆超时，请先登陆！");
            else
            {
                string id = Request["ID"];
                string FullName = Request["FullName"];
                string Caption = Request["Caption"];
                string DepartmentID = Request["DepartmentID"];//暂未使用
                string Owner = Request["Owner"];
                string IsDelete = Request["IsDelete"];
                string Remark = Request["Remark"];

                tChart chart = !id.IsGuid() ? null : CacheData.GetChart(id.ToGuid());
                if (FullName.IsNullOrWhiteSpace())
                    res = new Success(-2, null, "流程图名称不可为空！");
                else if (!Owner.IsGuid())
                    res = new Success(-3, null, "所属用户不可为空！");
                else if (id.IsGuid() && chart == null)
                    res = new Success(-4, null, "当前流程图不存在！");
                else if (id.IsGuid() && ((User)sUser).UserName != CacheData.sysadmin && chart.Owner != ((User)sUser).ID)
                    res = new Success(-5, null, "非超级管理员或所属用户不可编辑！");
                else
                {
                    var obj = new tChart();
                    obj.FullName = FullName;
                    obj.Caption = Caption;
                    obj.Owner = Owner.ToGuid();
                    obj.IsDelete = IsDelete.IsExtChecked();
                    obj.Remark = Remark;

                    obj.UpdateTime = DateTime.Now;
                    obj.UpdateUser = ((User)sUser).ID;
                    if (id.IsGuid())
                    {
                        obj.ID = id.ToGuid();
                        obj.CreateTime = chart.CreateTime;
                        var isOK = NHibernateDal.Update<tChart>(obj);
                        res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");

                        CacheData.ClearChart(id.ToGuid());
                    }
                    else
                    {
                        obj.ID = Guid.NewGuid();
                        obj.CreateTime = DateTime.Now;
                        var isOK = NHibernateDal.Insert<tChart>(obj);
                        res = new Success(isOK != null ? 1 : 0, null, isOK != null ? "" : "数据库操作失败！");
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 删除/恢复流程图信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ChartDelete()
        {
            Success res = null;

            string id = Request["ID"];

            object sUser = Session["user"];

            if (!id.IsGuid())
                res = new Success(-2, null, "要删除的ID必须指定！");
            else if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已登陆超时，请先登陆！");
            else
            {
                var chart = CacheData.GetChart(id.ToGuid());
                if (chart == null)
                    res = new Success(-3, null, "当前流程图不存在！");
                else if (((User)sUser).UserName != CacheData.sysadmin && chart.Owner != ((User)sUser).ID)
                    res = new Success(-4, null, "非超级管理员或所属用户无权删除！");
                else
                {
                    chart.IsDelete = !chart.IsDelete;
                    chart.UpdateTime = DateTime.Now;
                    chart.UpdateUser = ((User)sUser).ID;
                    var isOK = NHibernateDal.Update<tChart>(chart);
                    res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");

                    CacheData.ClearChart(id.ToGuid());
                }
            }

            return Content(res.JSONSerialize());
        }

        #endregion

        #region 流程图权限管理

        /// <summary>
        /// 获取流程图授权用户及代码列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ChartCodeList()
        {
            Success res = null;

            object sUser = Session["user"];
            if (sUser != null)
            {
                var ChartID = Request["ChartID"];
                if (ChartID.IsGuid())
                {
                    var Where = NH.CreateWhere("ChartID", ChartID.ToGuid());
                    var list = NHibernateDal.Select<tUserChart>(Where);
                    res = new Success(1, list, "");
                }
                else
                    res = new Success(-1, null, "未指定流程图ID！");
            }
            else
                res = new Success(0, null, "您还未登陆或已超时！");

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 修改流程图授权用户及代码数据
        /// </summary>
        /// <returns></returns>
        public ActionResult ChartCodeUpdate()
        {
            Success res = null;

            object sUser = Session["user"];
            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已超时！");
            else
            {
                var ChartID = Request["ChartID"];

                var chart = !ChartID.IsGuid() ? null : CacheData.GetChart(ChartID.ToGuid());
                if (!ChartID.IsGuid())
                    res = new Success(-2, null, "未指定流程图ID！");
                else if (chart == null)
                    res = new Success(-3, null, "当前流程图不存在！");
                else if (((User)sUser).UserName != CacheData.sysadmin && chart.Owner != ((User)sUser).ID)
                    res = new Success(-4, null, "非超级管理员或所属用户无权修改！");
                else
                {
                    var UpdateCode = Request["UpdateCode"];
                    var list = UpdateCode.JSONDeserialize<List<ChartCode_Update>>();

                    var cid = ChartID.ToGuid();
                    var addList = new List<tUserChart>();
                    foreach (var item in list)
                    {
                        if (item.Code != 0)
                        {
                            var obj = new tUserChart();
                            obj.UserID = item.ID;
                            obj.ChartID = cid;
                            obj.Code = (byte)item.Code;
                            addList.Add(obj);
                        }

                        CacheData.ClearUserChartCodeList(item.ID);
                    }

                    var isOK = true;
                    if (list.Count > 0)
                    {
                        var delList = "from tUserChart Where ChartID = '" + ChartID + "' and UserID in ('" + string.Join("','", list.Select(p => p.ID.ToString().ToList())) + "')";
                        var delCount = NHibernateDal.Delete<tUserChart>(delList);
                        if (delCount == -1)
                        {
                            res = new Success(-5, null, "删除被取消授权的用户授权信息失败！强烈建议您直接再点次提交试试。");
                            isOK = false;
                        }
                    }

                    if (isOK && addList.Count > 0)
                    {
                        isOK = NHibernateDal.Insert<tUserChart>(addList);
                        if (isOK == false)
                            res = new Success(-6, null, "插入用户授权信息失败！强烈建议您直接再点次提交试试。");
                    }

                    if (isOK)
                        res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");
                }
            }

            return Content(res.JSONSerialize());
        }

        #endregion

        #region 流程图图形操作

        /// <summary>
        /// 新增指定Diagram内容
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult CanvasPut()
        {
            Success res = null;
            object sUser = Session["user"];

            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已超时！");
            else
            {
                string cid = Request["cid"];
                string id = Request["id"];
                string name = Request["name"];
                string xml = Request["xml"];

                if (!cid.IsGuid())
                    res = new Success(-1, null, "Web图ID不存在！");
                else if (name.IsNullOrWhiteSpace())
                    res = new Success(-1, null, "Diagram的Name不可为空！");
                else
                {
                    var oldObj = id.IsLong() ? NHibernateDal.Select<tChartDiagram>(id.ToLong()) : null;

                    if (id.IsLong() && oldObj == null)
                        res = new Success(-2, null, "此DiagramID对应的数据不存在！");
                    else if (!((User)sUser).IsOperChart(cid.ToGuid(), (byte)ChartCode.可编辑))
                        res = new Success(-3, null, "您没有权限进行此操作！");
                    else
                    {

                        //对xml没有<mxGraphModel></mxGraphModel>标记而从<root>开始的增加<mxGraphModel></mxGraphModel>
                        xml = xml == null ? "" : xml.Trim();
                        if (xml.Length > 6 && xml.Substring(0, 6) == "<root>")
                            xml = "<mxGraphModel>" + xml + "</mxGraphModel>";

                        var obj = new tChartDiagram();
                        obj.ChartID = cid.ToGuid();
                        obj.DiagramName = name;
                        obj.DiagramContent = xml;
                        obj.IsDelete = false;
                        obj.CreateTime = DateTime.Now;
                        obj.UpdateTime = DateTime.Now;
                        obj.UpdateUser = ((User)sUser).ID;
                        obj.Remark = "";

                        if (id.IsLong())
                        {
                            obj.ID = id.ToLong();
                            var isOK = NHibernateDal.Update<tChartDiagram>(obj);
                            res = new Success(isOK ? 1 : 0, id.ToLong(), isOK ? "" : "数据库操作失败！");

                            if (isOK && oldObj.DiagramContent != obj.DiagramContent) //记录流程图修改日志：主要为保留修改前内容及修改后内容
                            {
                                var clog = new tLogChartDiagram();
                                clog.ChartDiagramID = id.ToLong();
                                clog.CreateTime = obj.UpdateTime;
                                clog.UserID = obj.UpdateUser;
                                clog.BakContent = oldObj.DiagramContent;
                                clog.UpdContent = obj.DiagramContent;
                                NHibernateDal.Insert<tLogChartDiagram>(clog);
                            }
                        }
                        else
                        {
                            var insId = NHibernateDal.Insert<tChartDiagram>(obj);
                            res = new Success(insId != null ? 1 : 0, insId, insId != null ? "" : "数据库操作失败！");
                        }
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 删除指定Diagram内容
        /// </summary>
        /// <returns></returns>
        public ActionResult CanvasRemove()
        {
            Success res = null;

            object sUser = Session["user"];

            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已超时！");
            else
            {
                var cid = Request["cid"];
                var id = Request["id"];
                if (!cid.IsGuid() || !id.IsLong())
                    res = new Success(-2, null, "Web图ID不存在或Diagram的ID不存在！");
                else
                {
                    if (!((User)sUser).IsOperChart(cid.ToGuid(), (byte)ChartCode.可删除))
                        res = new Success(-3, null, "您没有权限删除此流程图的Diagram图！");
                    else
                    {
                        var obj = NHibernateDal.Select<tChartDiagram>(id.ToLong());
                        if (obj == null)
                            res = new Success(-4, null, "此Diagram数据不存在！");
                        else if (obj.ChartID != cid.ToGuid())
                            res = new Success(-5, null, "此Diagram数据不属于当前Web图！");
                        else
                        {
                            obj.IsDelete = !obj.IsDelete;
                            obj.UpdateTime = DateTime.Now;
                            obj.UpdateUser = ((User)sUser).ID;
                            var isOK = NHibernateDal.Update<tChartDiagram>(obj);
                            res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");
                        }
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 获取Diagram的绘图图形数据
        /// </summary>
        /// <returns></returns>
        public ActionResult CanvasGet()
        {
            Success res = null;

            object sUser = Session["user"];
            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已超时！");
            else
            {
                var cid = Request["cid"];
                var id = Request["id"];
                if (!cid.IsGuid() || !id.IsLong())
                    res = new Success(-2, null, "Web图ID不存在或Diagram的ID不存在！");
                else
                {
                    if (!((User)sUser).IsOperChart(cid.ToGuid(), (byte)ChartCode.仅查看))
                        res = new Success(-3, null, "您没有权限查看此流程图的Diagram图！");
                    else
                    {
                        var obj = NHibernateDal.Select<tChartDiagram>(id.ToLong());
                        if (obj == null)
                            res = new Success(-4, null, "此Diagram数据不存在！");
                        else if (obj.ChartID != cid.ToGuid())
                            res = new Success(-5, null, "此Diagram数据不属于当前Web图！");
                        else
                            res = new Success(1, obj, "");
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 获取Diagrams数据列表
        /// </summary>
        /// <returns></returns>
        public ActionResult CanvasGetNames()
        {
            Success res = null;

            object sUser = Session["user"];
            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已超时！");
            else
            {
                var cid = Request["cid"];
                var IsDelete = Request["IsDelete"] ?? "0"; //是否显示删除的内容：0-仅显示未删除，1-仅显示已删除，2-所有
                if (!cid.IsGuid())
                    res = new Success(-2, null, "Web图ID不存在！");
                else
                {
                    if (!((User)sUser).IsOperChart(cid.ToGuid(), (byte)ChartCode.仅查看))
                        res = new Success(-3, null, "您没有权限查看此流程图的Diagram图！");
                    else
                    {
                        var Where = NH.CreateWhere("ChartID", cid.ToGuid());
                        if (IsDelete == "0")
                            Where.Add("IsDelete", false);
                        else if (IsDelete == "1")
                            Where.Add("IsDelete", true);

                        var list = NHibernateDal.Select<tChartDiagram>(Where, NH.CreateOrderBy("UpdateTime", OrderByType.Desc));
                        res = new Success(1, list, "");
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 查询Diagram名称是否已经存在
        /// </summary>
        /// <returns></returns>
        public ActionResult CanvasIsExists()
        {
            Success res = null;

            object sUser = Session["user"];
            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已超时！");
            else
            {
                var cid = Request["cid"];
                var name = Request["name"];
                if (!cid.IsGuid() || name.IsNullOrWhiteSpace())
                    res = new Success(-2, null, "Web图ID不存在或Diagram名称不存在！");
                else
                {
                    var where = NH.CreateWhere("ChartID", cid.ToGuid());
                    where.Add("DiagramName", name.Trim());
                    var list = NHibernateDal.Select<tChartDiagram>(where);
                    if (list.Count == 0)
                        res = new Success(1, null, "");
                    else
                        res = new Success(0, null, "此Diagram名称已存在！");
                }
            }

            return Content(res.JSONSerialize());
        }

        /// <summary>
        /// 对Diagram进行重命名与备注
        /// </summary>
        /// <returns></returns>
        public ActionResult CanvasReName()
        {
            Success res = null;

            object sUser = Session["user"];

            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已超时！");
            else
            {
                var cid = Request["cid"];
                var id = Request["id"];
                if (!cid.IsGuid() || !id.IsLong())
                    res = new Success(-2, null, "Web图ID不存在或Diagram的ID不存在！");
                else
                {
                    if (!((User)sUser).IsOperChart(cid.ToGuid(), (byte)ChartCode.可编辑))
                        res = new Success(-3, null, "您没有权限操作此流程图的Diagram图！");
                    else
                    {
                        var name = Request["name"];
                        var remark = Request["remark"];

                        var obj = NHibernateDal.Select<tChartDiagram>(id.ToLong());
                        if (obj == null)
                            res = new Success(-4, null, "此Diagram数据不存在！");
                        else if (obj.ChartID != cid.ToGuid())
                            res = new Success(-5, null, "此Diagram数据不属于当前Web图！");
                        else
                        {
                            var where = NH.CreateWhere("ChartID", cid.ToGuid());
                            where.Add("DiagramName", name.Trim());
                            var list = NHibernateDal.Select<tChartDiagram>(where);
                            if (list.Count > 0 && list.FirstOrDefault().ID != id.ToLong())
                                res = new Success(-6, null, "此Diagram名称已存在！");
                            else
                            {
                                obj.DiagramName = name.IsNullOrWhiteSpace() ? obj.DiagramName : name.Trim();
                                obj.Remark = remark.IsNullOrWhiteSpace() ? obj.Remark : remark.Trim();

                                obj.UpdateTime = DateTime.Now;
                                obj.UpdateUser = ((User)sUser).ID;
                                var isOK = NHibernateDal.Update<tChartDiagram>(obj);
                                res = new Success(isOK ? 1 : 0, null, isOK ? "" : "数据库操作失败！");
                            }
                        }
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        #endregion

        #region 流程图图形日志

        public ActionResult DiagramLogList()
        {
            Success res = null;

            object sUser = Session["user"];
            if (sUser == null)
                res = new Success(-1, null, "您还未登陆或已超时！");
            else
            {
                var cid = Request["cid"];
                var id = Request["id"];
                if (!cid.IsGuid() || !id.IsLong())
                    res = new Success(-2, null, "Web图ID不存在或Diagram的ID不存在！");
                else
                {
                    if (!((User)sUser).IsOperChart(cid.ToGuid(), (byte)ChartCode.仅查看))
                        res = new Success(-3, null, "您没有权限查看此流程图的Diagram图！");
                    else
                    {
                        var obj = NHibernateDal.Select<tChartDiagram>(id.ToLong());
                        if (obj == null)
                            res = new Success(-4, null, "此Diagram数据不存在！");
                        else if (obj.ChartID != cid.ToGuid())
                            res = new Success(-5, null, "此Diagram数据不属于当前Web图！");
                        else
                        {
                            var list = NHibernateDal.Select<tLogChartDiagram>(NH.CreateWhere("ChartDiagramID", id.ToLong()));
                            foreach(var item in list)
                            {
                                item.BakContent = item.BakContent.Replace("<", "&lt;").Replace(">", "&gt;");
                                item.UpdContent = item.UpdContent.Replace("<", "&lt;").Replace(">", "&gt;");
                            }
                            res = new Success(1, list, "");
                        }
                    }
                }
            }

            return Content(res.JSONSerialize());
        }

        #endregion

    }
}